<?php

namespace Biz\service\brand;

use Biz\model\brand\CustomCategory as mCustomCategory;
use Biz\model\brand\CustomCategoryWiki as mCustomCategoryWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\module\Classes\wiki\Infos;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Biz\service\wiki\Wiki;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\tools\BlockType;

class BrandCustomCategory
{
    public static function getCategoryList($brandId)
    {
        $result = [];
        $basicIds = mWikiBasic::selectByWhere(['basic_state' => mWikiBasic::STATE_ONLINE, 'brand_id' => $brandId], 'id');
        if ($basicIds) {
            $result[] = [
                'category_id' => "0",
                'title' => '全部',
                'sort' => "0",
            ];
            //校验商品分类
//            $rs = BrandEquityVerificationService::checkOneSourceStatus($brandId, SourceRightsInterface::SHOW_CATE,true);
//
//            if (!$rs) {
//                return $result;
//            }
            $where['brand_id'] = $brandId;
            $where['category_state'] = mCustomCategory::STATE_NORMAL;
            $is_sort = BrandEquityVerificationService::checkOneSourceStatus($brandId, SourceRightsInterface::CUSTOM_CLASSIFY, true);
            if ($is_sort) {
                $where['ORDER'] = ['sort' => 'ASC', 'id' => 'ASC'];
            }
            $list = mCustomCategory::selectByWhere($where);
            $categoryWikiArr = mCustomCategoryWiki::selectByWhere(['brand_id' => $brandId, 'custom_state' => mCustomCategoryWiki::STATE_NORMAL]);
            $categoryWikiList = [];
            foreach ($categoryWikiArr as $row) {
                if (in_array($row['basic_id'], $basicIds)) {
                    $categoryWikiList[$row['category_id']][] = $row['basic_id'];
                }
            }
            foreach ($list as $row) {
                if (isset($categoryWikiList[$row['id']])) {
                    $result[] = [
                        'category_id' => $row['id'],
                        'title' => $row['title'],
                        'sort' => $row['sort'],
                    ];
                }
            }
        }
        return $result;
    }

    public static function bGetCategoryList($brandId)
    {
        $result[] = [
            'category_id' => "0",
            'title' => '全部',
            'sort' => "0",
        ];
        $list = mCustomCategory::selectByWhere(['brand_id' => $brandId, 'category_state' => mCustomCategory::STATE_NORMAL, "ORDER" => ['sort' => 'ASC', 'id' => 'ASC']]);
        foreach ($list as $row) {
            $result[] = [
                'category_id' => $row['id'],
                'title' => $row['title'],
                'sort' => $row['sort']
            ];
        }
        return $result;
    }

    public static function editCategory($brandId, $data)
    {
        $dataCategoryIds = array_column($data, 'category_id');
        $dataCategoryIds = array_filter($dataCategoryIds);

        $list = mCustomCategory::selectByWhere(['category_state' => mCustomCategory::STATE_NORMAL, 'brand_id' => $brandId]);
        $categoryIds = array_column($list, 'id');
        $delCategoryIds = array_diff($categoryIds, $dataCategoryIds);
        foreach ($delCategoryIds as $id) {
            self::delCategory($brandId, $id);
        }
        foreach ($data as $row) {
            if ($row['category_id']) {
                mCustomCategory::updateData(['sort' => $row['sort'], 'title' => $row['title']], ['id' => $row['category_id']]);
            } else {
                mCustomCategory::insertData(['sort' => $row['sort'], 'title' => $row['title'], 'brand_id' => $brandId]);
            }
        }
        return true;
    }

    public static function delCategory($brandId, $categoryId)
    {
        if ((int)$categoryId > 0) {
            mCustomCategory::updateData(['category_state' => mCustomCategory::STATE_DEL], [
                'id' => $categoryId,
                'brand_id' => $brandId,
                'category_state[!]' => mCustomCategory::STATE_DEL
            ]);
            mCustomCategoryWiki::updateData(['custom_state' => mCustomCategoryWiki::STATE_CANCEL], [
                'category_id' => $categoryId,
                'brand_id' => $brandId,
                'custom_state' => mCustomCategoryWiki::STATE_NORMAL
            ]);
        }
        return true;
    }

    public static function bGetCategoryWikiList($brandId, $categoryId = 0)
    {
        $result = [];

        $categoryWikiList = mCustomCategoryWiki::selectByWhere(['category_id' => $categoryId, 'brand_id' => $brandId, 'custom_state' => mCustomCategoryWiki::STATE_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'DESC']]);
        $basicIds = $categoryWikiList ? array_column($categoryWikiList, 'basic_id') : [];

        $basicWikiList = $basicIds ? mWikiBasic::selectByWhere(['basic_state' => mWikiBasic::STATE_ONLINE, 'brand_id' => $brandId, 'id' => $basicIds]) : [];
        $basicWikiList = $basicWikiList ? array_column($basicWikiList, null, 'id') : [];

        $spuList = $basicIds ? mWiki::selectByWhere(['brand_id' => $brandId, 'is_default' => 1, 'status[!]' => mWiki::STATUS_DEL, 'basic_id' => $basicIds, 'is_official' => 1]) : [];
        $spuList = $spuList ? array_column($spuList, null, 'basic_id') : [];

        foreach ($categoryWikiList as $row) {
            $basicId = $row['basic_id'];
            $wikiSpuInfo = isset($spuList[$basicId]) ? $spuList[$basicId] : [];
            if ($wikiSpuInfo) {
                if (isset($basicWikiList[$basicId])) {
                    $result[$basicId] = [
                        'spu_id' => $wikiSpuInfo['id'],
                        'wiki_title' => $basicWikiList[$basicId]['title'],
                        'spu_title' => $wikiSpuInfo['title'],
                        'wiki_id' => $wikiSpuInfo['basic_id'],
                        'sort' => $row['sort'],
                        'custom_state' => $row['custom_state'],
                        'cover_img' => $wikiSpuInfo['cover_img']
                    ];
                }
            }
        }
        return $result;
    }

    public static function searchCategoryWiki($brandId, $categoryId = 0, $title = '')
    {
        $list = [];
        $basicWhere = ['basic_state' => mWikiBasic::STATE_ONLINE, 'brand_id' => $brandId];
        $categoryBasicIds = [];
        if (!empty($title)) {
            if (is_numeric($title)) {
                $basicWhere['id'] = $title;
            } else {
                $basicWhere['title[~]'] = $title;
            }
        } else {
            $categoryBasicIds = mCustomCategoryWiki::selectByWhere(
                ['brand_id' => $brandId, 'category_id' => $categoryId, 'custom_state' => mCustomCategoryWiki::STATE_NORMAL, 'ORDER' => ['sort' => 'ASC']],
                'basic_id'
            );
        }
        $basicWikiList = mWikiBasic::selectByWhere($basicWhere);
        $basicIds = array_column($basicWikiList, 'id');
        $basicWikiList = array_column($basicWikiList, null, 'id');
        $spuList = $basicIds ? mWiki::selectByWhere(['brand_id' => $brandId, 'is_default' => 1, 'status[!]' => mWiki::STATUS_DEL, 'basic_id' => $basicIds, 'is_official' => 1]) : [];
        $spuList = $spuList ? array_column($spuList, null, 'basic_id') : [];
        foreach ($categoryBasicIds as $basicId) {
            if (isset($spuList[$basicId]) && isset($basicWikiList[$basicId]) && !isset($list[$basicId])) {
                $list[$basicId] = [
                    'spu_id' => $spuList[$basicId]['id'],
                    'wiki_title' => $basicWikiList[$basicId]['title'],
                    'spu_title' => $spuList[$basicId]['title'],
                    'wiki_id' => $spuList[$basicId]['basic_id'],
                    'sort' => 0,
                    'custom_state' => 0,
                    'cover_img' => $spuList[$basicId]['cover_img']
                ];
            }
        }
        foreach ($spuList as $basicId => $row) {
            if (isset($spuList[$basicId]) && isset($basicWikiList[$basicId]) && !isset($list[$basicId])) {
                $list[$basicId] = [
                    'spu_id' => $row['id'],
                    'wiki_title' => $basicWikiList[$basicId]['title'],
                    'spu_title' => $row['title'],
                    'wiki_id' => $row['basic_id'],
                    'sort' => 0,
                    'custom_state' => 0,
                    'cover_img' => $row['cover_img']
                ];
            }
        }
        return $list;
    }

    public static function editCategoryWiki($categoryId, $data, $brandId)
    {
        $dataWikiIds = json_decode($data, true);
        $dataWikiIds = !empty($dataWikiIds) ? $dataWikiIds : [];
        $basicList = mCustomCategoryWiki::selectByWhere(['category_id' => $categoryId, 'brand_id' => $brandId]);
        $basicIds = array_column($basicList, 'basic_id');
        $delWikiIds = array_diff($basicIds, $dataWikiIds);
        if ($delWikiIds) {
            mCustomCategoryWiki::updateData(['custom_state' => mCustomCategoryWiki::STATE_CANCEL], ['category_id' => $categoryId, 'basic_id' => $delWikiIds, 'brand_id' => $brandId]);
        }
        $sort = 0;
        foreach ($dataWikiIds as $basicId) {
            if (in_array($basicId, $basicIds)) {
                mCustomCategoryWiki::updateData(['sort' => $sort, 'custom_state' => mCustomCategoryWiki::STATE_NORMAL], ['category_id' => $categoryId, 'basic_id' => $basicId, 'brand_id' => $brandId]);
            } else {
                mCustomCategoryWiki::insertData(['category_id' => $categoryId, 'brand_id' => $brandId, 'basic_id' => $basicId, 'sort' => $sort, 'custom_state' => mCustomCategoryWiki::STATE_NORMAL]);
            }
            $sort++;
        }
        return true;
    }

    /**
     * 品牌主页使用
     * @param $brandId
     * @param $uid
     * @param int $page
     * @param int $categoryId
     * @param int $pageSize
     * @return array
     * @throws \Exception
     */
    public static function getWikiByCategoryId($brandId, $uid, $page = 1, $categoryId = 0, $pageSize = 20)
    {
        if ($categoryId == 0) {
            $result = self::getAllCategoryWiki($brandId, $uid, $page, $pageSize);
        } else {
            $result = self::getCategoryWiki($brandId, $uid, $page, $categoryId, $pageSize);
        }
        return $result;
    }

    private static function getAllCategoryWiki($brandId, $uid, $page, $pageSize = 20)
    {
        $page = $page ? $page : 1;
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $result = [];
        $categoryWikiWhere = [
            'category_id' => 0,
            'brand_id' => $brandId,
            'custom_state' => mCustomCategoryWiki::STATE_NORMAL,
            'ORDER' => ['sort' => 'ASC', 'id' => 'DESC'],
        ];
        $categoryWikiWhere['LIMIT'] = [0, 20];//todo 线上20条之外的删除后，可以删除代码
        $categoryBasicIds = mCustomCategoryWiki::selectByWhere($categoryWikiWhere, 'basic_id');
        $countCategoryBasicIds = count($categoryBasicIds);

        $allBasicIds = mWikiBasic::selectByWhere([
            'basic_state' => mWikiBasic::STATE_ONLINE,
            'brand_id' => $brandId,
            'ORDER' => ['id' => 'DESC']
        ], 'id');
        $allBasicIds = array_diff($allBasicIds, $categoryBasicIds);
        $count = mWikiBasic::selectCountWhere(['basic_state' => mWikiBasic::STATE_ONLINE, 'brand_id' => $brandId]);
        $isOver = $count < ($page * $pageSize) ? 1 : 0;

        $basicIds = [];
        $appendBasicIds = [];
        if ($page == 1) {
            $basicIds = $categoryBasicIds;
            if ($countCategoryBasicIds < 20) {
                $offset = ($page - 1) * $pageSize;
                $length = 20 - $countCategoryBasicIds;
                $appendBasicIds = array_slice($allBasicIds, $offset, $length);
            }
        } else {
            if ($countCategoryBasicIds > 0) {
                $offset = ($page - 2) * $pageSize + (20 - $countCategoryBasicIds);
            } else {
                $offset = ($page - 1) * $pageSize;
            }
            $length = $pageSize;
            $basicIds = array_slice($allBasicIds, $offset, $length);
        }

        $basicIds = array_merge($basicIds, $appendBasicIds);

        if ($basicIds) {
            $list = self::getBrandWikiListByBasicIds($brandId, $basicIds, Infos::FIELDS_GROUP_MASONRY_LIST, $uid);
            foreach ($basicIds as $basicId) {
                $info = isset($list[$basicId]) ? $list[$basicId] : [];
                if ($info) {
                    $statSign = basicStatSign::genStatSign(basicStatSign::MODULE_BRAND_HOME_WIKI_LIST, [
                        basicStatSign::EXTEND_KEY_OBJ_ID => $basicId,
                        basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_BASIC,
                    ], ['brand_id' => $brandId]);
                    $info['statSign'] = $statSign;
                    $result[] = $info;
                }
            }
        }
        return ['list' => array_values($result), 'is_over' => $isOver];
    }

    private static function getCategoryWiki($brandId, $uid, $page, $categoryId, $pageSize)
    {
        $page = $page ? $page : 1;
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $result = [];
        $categoryWikiWhere = [
            'category_id' => $categoryId,
            'brand_id' => $brandId,
            'custom_state' => mCustomCategoryWiki::STATE_NORMAL,
            'ORDER' => ['sort' => 'ASC', 'id' => 'DESC'],
        ];
        $count = mCustomCategoryWiki::selectCountWhere($categoryWikiWhere);
        $categoryWikiWhere['LIMIT'] = $limit;
        $isOver = $count < ($page * $pageSize) ? 1 : 0;
        $categoryWikiList = mCustomCategoryWiki::selectByWhere($categoryWikiWhere);
        $basicIds = [];
        $categoryBasicIds = [];
        foreach ($categoryWikiList as $row) {
            $categoryBasicIds[] = $row['basic_id'];
            $basicIds[] = $row['basic_id'];
        }

        if ($basicIds) {
            $where = ['basic_state' => mWikiBasic::STATE_ONLINE, 'brand_id' => $brandId, 'id' => $basicIds];
            $basicIds = mWikiBasic::selectByWhere($where, 'id');
            $list = self::getBrandWikiListByBasicIds($brandId, $basicIds, Infos::FIELDS_GROUP_MASONRY_LIST, $uid);
            foreach ($basicIds as $basicId) {
                $info = isset($list[$basicId]) ? $list[$basicId] : [];
                if ($info) {
                    $statSign = basicStatSign::genStatSign(basicStatSign::MODULE_BRAND_HOME_WIKI_LIST, [
                        basicStatSign::EXTEND_KEY_OBJ_ID => $basicId,
                        basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_BASIC,
                    ], ['brand_id' => $brandId]);
                    $info['statSign'] = $statSign;
                    $result[] = $info;
                }
            }
        }
        return ['list' => $result, 'is_over' => $isOver];
    }

    public static function getBrandWikiListByBasicIds($brandId, $basicIds, $fileldGroup = Infos::FIELDS_GROUP_MASONRY_LIST, $uid = 0)
    {
        $list = [];
        if ($brandId && $basicIds) {
            //grpc 调用
            //grpc 调用
            $wikiGrpcClient = \Wiki\GrpcClient::getInstance();
            $aRet = $wikiGrpcClient->getBrandWikiListByBasicIds([
                "brandId" => $brandId,
                'basicIds' => $basicIds,
                "fieldsGroup" => $fileldGroup,
                "uid" => $uid
            ]);

            if ($aRet['biz_code'] != 0) {
                return [];
            }
            $list = $aRet['result']['list'] ?? [];
            $list = array_values($list);
            $list = $list ? array_column($list, null, 'basic_id') : [];
        }
        return $list;
    }
}
